package manager

import event.SellChangedEvent
import ext.log
import mvc.model.HeatData
import org.json.JSONArray
import task.RefreshSellTask

object HeatManager : Runnable {
    var HeatDataInfos = emptyArray<HeatData>()
    private val controlTask = HeatControlTask()

    override fun run() {
        try {
            val result = NetworkManager.refreshControlHeatData()
            log("---$result", "温度控制数据")
            val arr = JSONArray(result)
            val len = arr.length()
            HeatDataInfos = Array(len) { HeatData.withJson(arr.getJSONObject(it)) }
        } catch (e: Exception) {
            e.printStackTrace()
            AsyncTask.postDelayed(this, 60 * 1000)
        }
    }

    fun refreshAsync() {
        AsyncTask.post(this)
        AsyncTask.removeCallbacks(controlTask)
        AsyncTask.post(controlTask)
    }

    fun control() {

        if (StatusManager.status.isFault) {
            log("发生故障停止温度控制")
            DeliveryManager.setOvenTempValue(0, 0, 0)
            return
        }

        /**
         * 开启售卖的时候才开启红外加热
         */
        if (RefreshSellTask.SellStatus == SellChangedEvent.START) {

            for (info in HeatDataInfos) {
                if (info.isExist()) {
                    log(info.toString(), "开始温度控制")
                    DeliveryManager.setOvenTempValue(
                        info.minTempValue,
                        info.maxTempValue,
                        info.timeOut * 60
                    )
                    return
                }
            }

            val info = HeatData.default()
            if (info.isExist()) {
                log("开始默认温度控制")
                DeliveryManager.setOvenTempValue(
                    info.minTempValue,
                    info.maxTempValue,
                    info.timeOut * 60
                )
                return
            }
        }

        DeliveryManager.setOvenTempValue(0, 0, 0)
    }

    private class HeatControlTask : Runnable {

        override fun run() {
            try {
                control()
            } catch (e: Exception) {
                e.printStackTrace()
            }

            AsyncTask.postDelayed(this, 60 * 1000)
        }
    }

}


